<template>
  <div>
    <el-card>
      <el-form :inline="true" :model="formData" class="demo-form-inline">
        <el-form-item label="项目">
          <el-select
            v-model="formData.project"
            placeholder="项目"
            @change="getFiles"
          >
            <el-option
              v-for="item in projectOptions"
              :key="item.id"
              :label="item.projectName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="模块">
          <el-select v-model="formData.file" placeholder="文件名">
            <el-option
              v-for="item in fileOptions"
              :key="item.id"
              :label="item.fileName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="queryTestcases">生成</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="exportTestcaseToExcel">下载</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="add2TestPlain"
            >加入测试计划</el-button
          >
        </el-form-item>
        <!-- <el-form-item>
          <el-button type="primary" @click="onSubmit">加入模板</el-button>
        </el-form-item> -->
      </el-form>
    </el-card>

    <div class="testcasetable">
      <el-row :gutter="10">
        <el-col :span="24">
          <el-table
            ref="parentTable"
            :data="testCases"
            :row-class-name="tableRowClassName"
            style="width: 100%"
            highlight-current-row
          >
            <el-table-column type="expand">
              <template slot-scope="props">
                <el-table
                  :data="props.row.steps"
                  id="steps-table"
                  :highlight-current-row="props.$index === currentTableIndex"
                  @current-change="
                    handleCurrentChange(props.$index, props.row.steps)
                  "
                  @row-click="setRowIndex"
                >
                  <el-table-column type="index"></el-table-column>
                  <el-table-column label="步骤">
                    <template slot-scope="scope">
                      <el-input
                        type="textarea"
                        v-model="scope.row.step"
                        :rows="scope.row.rowCount"
                        @input="refreshRow(scope.row)"
                      ></el-input>
                    </template>
                  </el-table-column>
                  <el-table-column label="预期结果">
                    <template slot-scope="scope">
                      <el-input
                        type="textarea"
                        v-model="scope.row.result"
                        :rows="scope.row.rowCount"
                        @input="refreshRow(scope.row)"
                      ></el-input>
                    </template>
                  </el-table-column>
                </el-table>
              </template>
            </el-table-column>
            <el-table-column label="标题" prop="title"> </el-table-column>
            <el-table-column label="用例设计阶段" width="120">
              <template slot-scope="scope">
                <el-select v-model="scope.row.caseDesignPhase" placeholder="请选择">
                  <el-option
                    v-for="item in caseDesignPhase"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </template>
            </el-table-column>
             <el-table-column label="用例类型" width="120">
              <template slot-scope="scope">
                <el-select v-model="scope.row.caseType" placeholder="请选择">
                  <el-option
                    v-for="item in caseType"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="用例设计人" width="120">
              <template slot-scope="scope">
                <el-input v-model="scope.row.designer"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="添加" width="60">
              <template>
                <el-button type="text" @click="addRow"
                  ><i class="el-icon-circle-plus-outline"></i
                ></el-button>
              </template>
            </el-table-column>

            <el-table-column label="删除" width="60">
              <template>
                <el-button type="text" @click="delRow"
                  ><i class="el-icon-remove-outline"></i
                ></el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
    </div>

    <el-dialog title="选择测试计划" :visible.sync="testPlainDialog" width="30%">
      <el-select v-model="currentTestPlain">
        <el-option
          v-for="item in plainList"
          :key="item.plainId"
          :label="item.testPlainName"
          :value="item.plainId"
        >
        </el-option>
      </el-select>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="selectPlainConfirm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { getProjects, getTestPlain } from "@/api/project";
import { queryFile } from "@/api/file";
import {
  updateTestcase,
  addTestcase2Testplain,
  translateXmind2Test,
  exportTestcase
} from "@/api/testcase";
import { v4 as uuidv4 } from "uuid";
export default {
  data() {
    return {
      formData: {
        project: "",
        file: "",
      },
      projectOptions: [],
      fileOptions: [],
      testCases: [],
      testPlainDialog: false,
      plainList: [],
      projectId: "",
      currentTestPlain: "",
      selectTestcase: [],
      currentTableIndex: 0,
      currentTableRow: null,
      currentSteps: null,

      caseDesignPhase:[
        {
          label:"用例设计",
          value:"用例设计"
        }
      ],
      caseType:[
        {
          label:"集成测试",
          value:"集成测试"
        }
      ]
    };
  },
  methods: {
    tableRowClassName({ row, rowIndex }) {
      // console.log("rowIndex")
      if (rowIndex === 1) {
        // console.log(123)
        return "warning-row";
      } else if (rowIndex === 3) {
        return "success-row";
      }
      return "";
    },

    // handleRowClick(row,column){
    //   // console.log(row,column)
    // },

    setRowIndex(row) {
      this.currentTableRow = row;
    },
    handleCurrentChange(index, row) {
      this.currentTableIndex = index;
      this.currentSteps = row;
    },
    delRow() {
      if (this.currentSteps === null || this.currentTableRow == null) {
        return;
      }
      const { key } = this.currentTableRow;
      let index;
      for (let i = 0; i < this.currentSteps.length; i++) {
        if (key === this.currentSteps[i]["key"]) {
          index = i;
          break;
        }
      }
      this.currentSteps.splice(index, 1);
    },

    addRow() {
      if (this.currentSteps === null || this.currentTableRow == null) {
        return;
      }
      const { key } = this.currentTableRow;
      let index;
      for (let i = 0; i < this.currentSteps.length; i++) {
        if (key === this.currentSteps[i]["key"]) {
          index = i;
          break;
        }
      }
      this.currentSteps.splice(index + 1, 0, {
        key: uuidv4(),
        rowCount: 1,
        step: "",
        result: "",
      });
    },
    onSubmit() {
      console.log("submit!");
    },
    handleSelectionChange() {},
    refreshRow(row) {
      const { step, result } = row;
      let stepRow = step.split("\n").length;
      let resultRow = result.split("\n").length;
      let rowCount = stepRow > resultRow ? stepRow : resultRow;
      row["rowCount"] = rowCount;
    },
    getFiles(value) {
      this.projectId = value;
      queryFile(value).then((res) => {
        this.fileOptions = res.data;
      });
    },
    queryTestcases() {
      translateXmind2Test(this.formData.file).then((res) => {
        this.testCases = res.data;

        for (let i = 0; i < this.testCases.length; i++) {
          if (this.testCases[i]["steps"].length === 0) {
            this.testCases[i]["steps"].push({
              key: uuidv4(),
              rowCount: 1,
              step: "",
              result: "",
            });
          } else {
            for (let j = 0; j < this.testCases[i]["steps"].length; j++) {
              let rowCount = 0;
              let stepRow = this.testCases[i]["steps"][j]["step"]
                .trim()
                .split("\r\n").length;
              let resultRow = this.testCases[i]["steps"][j]["result"]
                .trim()
                .split("\r\n").length;
              rowCount = stepRow > resultRow ? stepRow : resultRow;
              this.testCases[i]["steps"][j]["rowCount"] = rowCount;
              this.testCases[i]["steps"][j]["key"] = uuidv4();
            }
          }

          this.$set(this.testCases[i], "designer", "");
          this.$set(this.testCases[i], "caseDesignPhase", "用例设计");
             this.$set(this.testCases[i], "caseType", "集成测试");
        }
      });
    },

    handleSelected(row, col, event) {
      // console.log(row.id);
      let list = this.testCases.filter((item) => {
        return item.id === row.id;
      });
      this.currentTestcase = list[0].desc;
    },

    exportTestcaseToExcel() {
     exportTestcase(this.testCases,"测试用例.xmind")
    // .then((res) => {
    //     const { data, headers } = res;
    //     const fileName = headers["content-disposition"].replace(
    //       /\w+;filename=(.*)/,
    //       "$1"
    //     );
    //     const blob = new Blob([data], { type: 'application/vnd.ms-excel' });
    //     let dom = document.createElement("a");
    //     let url = window.URL.createObjectURL(blob);
    //     dom.href = url;
    //     dom.download = decodeURI(fileName);
    //     dom.style.display = "none";
    //     document.body.appendChild(dom);
    //     dom.click();
    //     dom.parentNode.removeChild(dom);
    //     window.URL.revokeObjectURL(url);
    //   });
    },

    getSelected(selection, row) {
      this.selectTestcase = selection;
    },
    add2TestPlain() {
      this.testPlainDialog = true;
      getTestPlain(this.projectId).then((res) => {
        this.plainList = res.data;
      });
    },
    selectPlainConfirm() {
      let idList = [];

      this.selectTestcase.forEach((item) => {
        idList.push(item.id);
      });

      addTestcase2Testplain(
        this.currentTestPlain,
        this.formData.file,
        idList
      ).then((res) => {
        this.testPlainDialog = false;
        this.$message({
          message: res.msg,
          type: "success",
        });
      });
    },
  },
  mounted() {
    getProjects().then((res) => {
      this.projectOptions = res.data;
    });
  },
};
</script>

<style scoped>
.testcasetable {
  height: 100%;
}

.el-table .warning-row {
  background: rgb(83, 20, 222);
}

.el-table .success-row {
  background: #ee5c0d;
}
#steps-table .el-table__row {
  background: #89b2ec;
}
</style>